package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskMapper;
    @Autowired
    private CacheService cacheService;


    @Override
    public long addTask(Task task) {

        //添加任务到数据库(消息持久化)
        addTaskToDB(task);

        //添加任务到redis(缓存)
        addTaskToCache(task);
            //添加到list(执行任务)
            //添加到zset(预执行，五分钟预热)
        return task.getTaskId();

    }

    private void addTaskToCache(Task task) {
        if (cacheService == null) {
            log.error("CacheService 未正确注入");
            throw new RuntimeException("缓存服务不可用");
        }

        String key = task.getTaskType() + "_" + task.getPriority();
        //添加到list(执行任务)
        if (task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }//添加到zset(预执行，五分钟预热)
        else if (task.getExecuteTime() <= System.currentTimeMillis() + 5*1000*60){
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }

    }

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Override
    public void addTaskToDB(Task task) {

        //加入task info
        try {
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date( task.getExecuteTime()));
            taskMapper.insert(taskinfo);

            task.setTaskId(taskinfo.getTaskId());

            //加入task info log
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setStatus(TaskinfoLogs.Status.WAITING.getStatus());
            taskinfoLogs.setVersion(1);
            taskinfoLogsMapper.insert(taskinfoLogs);
        } catch (BeansException e) {
            // 记录日志
            log.error("添加任务到数据库失败", e);
            // 重新抛出异常，触发事务回滚
            throw new RuntimeException("任务添加失败", e);
        }

    }

    @Override
    public boolean cancelTask(Long taskId) {
        //数据库取消任务
        if (taskId == null)
            return false;
        Task task = new Task();;
        if (!cancleTaskFromDB(taskId, task, TaskinfoLogs.Status.CANCELLED.getStatus())) return false; // 成功取消任务

        removeTaskFromCache(task);

        return true;
    }

    private boolean cancleTaskFromDB(Long taskId, Task task,Integer status) {
        Taskinfo taskinfo = taskMapper.selectById(taskId);
        if (taskinfo != null) {

            taskMapper.deleteById(taskinfo.getTaskId());
//            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectOne(Wrappers.<TaskinfoLogs>lambdaQuery()
//                    .eq(TaskinfoLogs::getTaskId, taskinfo.getTaskId()));


            BeanUtils.copyProperties(taskinfo, task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());

//            System.out.printf("time:" + task.getExecuteTime());
            log.info("取消任务：{}", task.getExecuteTime());
            log.info("取消任务：{}", JSON.toJSONString(task));
//            taskinfoLogs.setStatus(TaskinfoLogs.Status.CANCELLED.getStatus());
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskinfo.getTaskId());
            if (taskinfoLogs != null) {
                // 设置新状态和版本号
                taskinfoLogs.setStatus(status);
                // MyBatis-Plus 会自动处理版本号的递增
                taskinfoLogsMapper.updateById(taskinfoLogs);
            }
            return true;
        }
        return false;
    }

    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));

        cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));

    }

    @Override
    public Task poll(int type, int priority) {
        Task task = null;

        try {
            String key = type + "_" + priority;

            //从redis中拉取数据  pop
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(task_json)) {
                task = JSON.parseObject(task_json, Task.class);

                //修改数据库信息
                cancleTaskFromDB(task.getTaskId(), task, ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("poll task exception");
        }


        return task;
    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        String token = cacheService.tryLock("FUTRUE_TASK_SYNC", 1000 * 30);

        if (StringUtils.isNotBlank(token)) {
            log.info("未来数据定时刷新---定时任务");

            //获取所有未来数据的集合key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {//future_100_50

                //获取当前数据的key  topic
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];

                //按照key和分值查询符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                //同步数据
                if (!tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    log.info("成功的将" + futureKey + "刷新到了" + topicKey);
                }else {
                    log.info("无数据刷新到执行列表");
                }
            }
        }
    }

    @PostConstruct
    @Scheduled(cron = "0 */1 * * * ?")
    public void reloadRedisFromDB() {

        log.info("开始从数据库刷新任务到缓存");
        //清除缓存
        cleanCache();

        //数据库获取所有小于未来5分钟的任务
        List<Taskinfo> taskinfos = taskMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, new Date(System.currentTimeMillis() + 1000 * 60 * 5)));
        log.info( "时间："+ System.currentTimeMillis() + 1000 * 60 * 5);
        log.info("从数据库获取任务：{}", taskinfos);
        if ( taskinfos != null && !taskinfos.isEmpty()) {
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
                log.info("从数据库刷新任务到缓存：{}", task);
            }
            log.info("从数据库刷新任务到缓存完成");
        }

    }

    private void cleanCache() {
        Set<String> FutureTask = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(FutureTask);
        Set<String> topicTask = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(topicTask);
    }

}
